package com.sky.Aspect;

import com.sky.AutoFIle.AutoFiles;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect
@Slf4j
public class AotoFileAspect {
    @Pointcut("execution(* com.sky.mapper.*.*(..)) &&@annotation(com.sky.AutoFIle.AutoFiles)")
    public void po() {

    }
   @Before("po()")
    public void before(JoinPoint joinPoint) {
        log.info("正在加强方法{}",joinPoint.getSignature().getName());
       Object[] args = joinPoint.getArgs();//获取参数

       MethodSignature signature =(MethodSignature) joinPoint.getSignature();
       AutoFiles annotation = signature.getMethod().getAnnotation(AutoFiles.class);//获取注解
       OperationType value = annotation.value();
      if (args ==null || args.length==0){
          return;
      }
     //准备数据
       Long currentId = BaseContext.getCurrentId();
       LocalDateTime now = LocalDateTime.now();
       Object arg = args[0];//对参数里的方法进行反射
       if (value == OperationType.INSERT){
           try {
               Method declaredMethod = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
               Method declaredMethod1 = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
               Method declaredMethod2 = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
               Method declaredMethod3 = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
               declaredMethod.invoke(arg,now);
               declaredMethod1.invoke(arg,currentId);
               declaredMethod2.invoke(arg,now);
               declaredMethod3.invoke(arg,currentId);
           } catch (Exception e) {
               throw new RuntimeException(e);
           }


       }
       else if (value == OperationType.UPDATE){
           try {
               Method declaredMethod2 = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
               Method declaredMethod3 = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
               declaredMethod2.invoke(arg,now);
               declaredMethod3.invoke(arg,currentId);
           } catch (Exception e) {
               throw new RuntimeException(e);
           }


       }


   }
}
